package com.polaris.live.common.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter

/**
 * ViewPagerAdapter
 *
 * @author Created by lucas on 2023/10/16 14:49
 * @since 1.0.0
 */
open class ViewPagerAdapter(
    fragments: List<Fragment>,
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle,
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    private val fragmentHashCodes = arrayListOf<Long>()

    constructor(
        fragments: List<Fragment>,
        activity: FragmentActivity,
    ) : this(fragments, activity.supportFragmentManager, activity.lifecycle)

    constructor(
        fragments: List<Fragment>,
        fragment: Fragment,
    ) : this(fragments, fragment.childFragmentManager, fragment.lifecycle)

    // 数据集
    private val fragmentList = mutableListOf<Fragment>()

    init {
        fragmentList.addAll(fragments)
        for (fragment in fragments) {
            fragmentHashCodes.add(fragment.hashCode().toLong())
        }
    }

    fun setFragments(fragments: List<Fragment>) {
        fragmentList.clear()
        fragmentList.addAll(fragments)
        fragmentHashCodes.clear()
        for (fragment in fragments) {
            fragmentHashCodes.add(fragment.hashCode().toLong())
        }
        notifyDataSetChanged()
    }

    fun removeFragment(position: Int){
        fragmentList.removeAt(position)
        fragmentHashCodes.removeAt(position)
        notifyDataSetChanged()
    }

    fun addFragment(fragment: Fragment) {
        fragmentList.add(fragment)
        fragmentHashCodes.add(fragment.hashCode().toLong())
        notifyDataSetChanged()
    }

    override fun getItemId(position: Int): Long {
        return fragmentList[position].hashCode().toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        return fragmentHashCodes.contains(itemId)
    }

    override fun getItemCount() = fragmentList.size

    override fun createFragment(position: Int) = fragmentList[position]

}